﻿using System;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.UI.ApplicationSettings;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;

namespace CrateMayhem.WinRT
{
    sealed partial class App
    {
        private Popup settingsPopup;

        public App()
        {
            InitializeComponent();
            Suspending += OnSuspending;
            Global.Init();
        }

        protected override void OnLaunched(LaunchActivatedEventArgs args)
        {
            var rootFrame = Window.Current.Content as Frame;

            if (rootFrame == null)
            {
                rootFrame = new Frame();

                if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    //TODO: Load state from previously suspended application
                }

                SettingsPane.GetForCurrentView().CommandsRequested += OnAppCommandsRequested;
                Window.Current.Content = rootFrame;
            }

            if (rootFrame.Content == null)
            {
                if (!rootFrame.Navigate(typeof(MainPage), args.Arguments))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            Window.Current.Activate();
        }

        private void OnAppCommandsRequested(SettingsPane sender, SettingsPaneCommandsRequestedEventArgs args)
        {
            const int optionsWidth = 346;

            var about = new SettingsCommand("options", "Options", h =>
                {
                    var bounds = Window.Current.Bounds;

                    if (settingsPopup != null)
                    {
                        settingsPopup.IsOpen = false;
                        settingsPopup = null;
                    }

                    var options = new Options { Width = optionsWidth, Height = bounds.Height };
                    settingsPopup = new Popup
                        {
                            Child = options,
                            IsLightDismissEnabled = true,
                            Width = optionsWidth,
                            Height = bounds.Height,
                            IsOpen = true
                        };
                    settingsPopup.SetValue(Canvas.LeftProperty, bounds.Width - settingsPopup.Width);
                    settingsPopup.SetValue(Canvas.TopProperty, 0);

                });
            args.Request.ApplicationCommands.Add(about);
        }

        private void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            //TODO: Save application state and stop any background activity
            deferral.Complete();
        }
    }
}
